.TH std::enable_shared_from_this::operator= 3 "2024.06.10" "http://cppreference.com" "C++ Standard Libary"
.SH NAME
std::enable_shared_from_this::operator= \- std::enable_shared_from_this::operator=

.SH Synopsis
   enable_shared_from_this& operator=( const enable_shared_from_this      \fI(since C++11)\fP
   &rhs ) noexcept;

   Does nothing; returns *this.

.SH Parameters

   rhs - another enable_shared_from_this to assign to *this

.SH Return value

   *this

.SH Notes

   The exposition-only std::weak_ptr<T> member weak-this is not affected by this
   assignment operator.

.SH Example

   Note: enable_shared_from_this::operator= is defined as protected in order to prevent
   accidental slicing but allow derived classes to have default assignment operators.


// Run this code

 #include <iostream>
 #include <memory>

 class SharedInt : public std::enable_shared_from_this<SharedInt>
 {
 public:
     explicit SharedInt(int n) : mNumber(n) {}
     SharedInt(const SharedInt&) = default;
     SharedInt(SharedInt&&) = default;
     ~SharedInt() = default;

     // Both assignment operators use enable_shared_from_this::operator=
     SharedInt& operator=(const SharedInt&) = default;
     SharedInt& operator=(SharedInt&&) = default;

     int number() const { return mNumber; }

 private:
     int mNumber;
 };

 int main()
 {
     std::shared_ptr<SharedInt> a = std::make_shared<SharedInt>(2);
     std::shared_ptr<SharedInt> b = std::make_shared<SharedInt>(4);
     *a = *b;

     std::cout << a->number() << '\\n';
 }

.SH Output:

 4

.SH See also

   shared_ptr smart pointer with shared object ownership semantics
   \fI(C++11)\fP    \fI(class template)\fP
